package com.michaelbulava.TFS.tasks.workspaces;

import com.intellij.openapi.progress.ProgressIndicator;
import com.michaelbulava.TFS.persistence.IdeaPersistenceStoreProvider;
import com.michaelbulava.TFS.tasks.BackgroundableTask;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient;
import com.microsoft.tfs.core.clients.versioncontrol.Workstation;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;
import com.microsoft.tfs.util.xml.XMLException;

import java.io.FileNotFoundException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by MichaelA on 8/4/2015.
 */
public class QueryLocalWorkspacesTask  extends BackgroundableTask {
    private final VersionControlClient vcClient;
    private List<Workspace> workspaces;

    public QueryLocalWorkspacesTask(TFSTeamProjectCollection collection) {
        super(null, "Querying local workspaces...", false);
        this.vcClient = collection.getVersionControlClient();
    }

    @Override
    protected boolean runInBackground() {
        return false;
    }

    @Override
    public void run(ProgressIndicator progressIndicator) {
        String messageFormat = "Querying workspaces on {0}";
        String message = MessageFormat.format(messageFormat, new Object[]{this.vcClient.getConnection().getName()});
        progressIndicator.setText(message);

        AtomicReference<Workspace[]> workspacesHolder = new AtomicReference<Workspace[]>();

        try{
            Workstation.getCurrent(this.vcClient.getConnection().getPersistenceStoreProvider())
            //Workstation.getCurrent(IdeaPersistenceStoreProvider.INSTANCE)
                    .updateWorkspaceInfoCache(this.vcClient, this.vcClient.getConnection()
                            .getAuthorizedTFSUser().toString(), workspacesHolder);
        }catch(XMLException e){
            if (!(e.getCause() instanceof FileNotFoundException))
                throw e;
        }
        //Using Arrays.asList over the returned array casts the value to an Arraylist hosted in java.util.Arrays,
        //which doesn't allow for removing items.
        Workspace[] found = workspacesHolder.get();
        if (found != null && found.length > 0){
            this.workspaces = new ArrayList<Workspace>();
            for(int i = 0; i < found.length; i++){
                this.workspaces.add(found[i]);
            }
        } else {
            this.workspaces = new ArrayList<Workspace>();
        }
    }

    public List<Workspace> getWorkspaces()
    {
        return this.workspaces;
    }
}